Socket
Socket
Sign inDemoInstall

linkify-it

Package Overview
Dependencies
1
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    linkify-it

Links recognition library with FULL unicode support


Version published
Weekly downloads
7.4M
increased by6%
Maintainers
1
Install size
39.7 kB
Created
Weekly downloads
 

Package description

What is linkify-it?

The linkify-it package is a tool for finding links such as URLs and email addresses in plain text and converting them into clickable hyperlinks. It is highly customizable and allows developers to tweak the link recognition to suit their needs.

What are linkify-it's main functionalities?

URL Recognition

This feature allows the detection of URLs within a text string and provides details about the recognized URLs, such as the index of the match within the string.

const linkify = require('linkify-it')();
console.log(linkify.match('Visit http://example.com for more information.'));

Email Recognition

With this feature, linkify-it can identify email addresses in text and treat them as mailto: links, which can be useful for creating clickable email links.

const linkify = require('linkify-it')();
linkify.add('mailto:', 'mailto:');
console.log(linkify.match('Contact us at: info@example.com'));

Custom Schema

This feature allows developers to add custom schemas and protocols to be recognized by linkify-it, enabling the detection of non-standard or less common link types.

const linkify = require('linkify-it')();
linkify.add('git:', 'http:');
console.log(linkify.match('Clone the repo at git://github.com/user/repo.git'));

TLD Customization

Linkify-it allows for the addition of custom top-level domains (TLDs) to its list, which can be useful for recognizing and linking to URLs with non-standard TLDs.

const linkify = require('linkify-it')();
linkify.tlds('my', true);
console.log(linkify.match('Check out this cool site: example.my'));

Other packages similar to linkify-it

Readme

Source

linkify-it

Build Status NPM version Coverage Status Gitter

Links recognition library with FULL unicode support. Focused on high quality link patterns detection in plain text.

Demo

Why it's awesome:

  • Full unicode support, with astral characters!
  • International domains support.
  • Allows rules extension & custom normalizers.

Install

npm install linkify-it --save

Browserification is also supported.

Usage examples

Example 1
var linkify = require('linkify-it')();

// Reload full tlds list & add unofficial `.onion` domain.
linkify
  .tlds(require('tlds'))          // Reload with full tlds list
  .tlds('onion', true)            // Add unofficial `.onion` domain
  .linkify.add('git:', 'http:')   // Add `git:` ptotocol as "alias"
  .linkify.add('ftp:', null)      // Disable `ftp:` ptotocol
  .set({ fuzzyIP: true });        // Enable IPs in fuzzy links (without schema)

console.log(linkify.test('Site github.com!'));  // true

console.log(linkify.match('Site github.com!')); // [ {
                                                //   schema: "",
                                                //   index: 5,
                                                //   lastIndex: 15,
                                                //   raw: "github.com",
                                                //   text: "github.com",
                                                //   url: "http://github.com",
                                                // } ]
Example 2. Add twitter mentions handler
linkify.add('@', {
  validate: function (text, pos, self) {
    var tail = text.slice(pos);

    if (!self.re.twitter) {
      self.re.twitter =  new RegExp(
        '^([a-zA-Z0-9_]){1,15}(?!_)(?=$|' + self.re.src_ZPCc + ')'
      );
    }
    if (self.re.twitter.test(tail)) {
      // Linkifier allows punctuation chars before prefix,
      // but we additionally disable `@` ("@@mention" is invalid)
      if (pos >= 2 && tail[pos - 2] === '@') {
        return false;
      }
      return tail.match(self.re.twitter)[0].length;
    }
    return 0;
  },
  normalize: function (match) {
    match.url = 'https://twitter.com/' + match.url.replace(/^@/, '');
  }
});

API

API documentation

new LinkifyIt(schemas, options)

Creates new linkifier instance with optional additional schemas. Can be called without new keyword for convenience.

By default understands:

  • http(s)://... , ftp://..., mailto:... & //... links
  • "fuzzy" links and emails (google.com, foo@bar.com).

schemas is an object, where each key/value describes protocol/rule:

  • key - link prefix (usually, protocol name with : at the end, skype: for example). linkify-it makes shure that prefix is not preceeded with alphanumeric char.
  • value - rule to check tail after link prefix
    • String - just alias to existing rule
    • Object
      • validate - validator function (should return matched length on success), or RegExp.
      • normalize - optional function to normalize text & url of matched result (for example, for twitter mentions).

options:

  • fuzzyLink - recognige URL-s without http(s):// head. Default true.
  • fuzzyIP - allow IPs in fuzzy links above. Can conflict with some texts like version numbers. Default false.
  • fuzzyEmail - recognize emails without mailto: prefix. Default true.

.test(text)

Searches linkifiable pattern and returns true on success or false on fail.

.pretest(text)

Quick check if link MAY BE can exist. Can be used to optimize more expensive .test() calls. Return false if link can not be found, true - if .test() call needed to know exactly.

.testSchemaAt(text, name, offset)

Similar to .test() but checks only specific protocol tail exactly at given position. Returns length of found pattern (0 on fail).

.match(text)

Returns Array of found link matches or null if nothing found.

Each match has:

  • schema - link schema, can be empty for fuzzy links, or // for protocol-neutral links.
  • index - offset of matched text
  • lastIndex - index of next char after mathch end
  • raw - matched text
  • text - normalized text
  • url - link, generated from matched text

.tlds(list[, keepOld])

Load (or merge) new tlds list. Those are needed for fuzzy links (without schema) to avoid false positives. By default:

  • 2-letter root zones are ok.
  • biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф are ok.
  • encoded (xn--...) root zones are ok.

If that's not enougth, you can reload defaults with more detailed zones list.

.add(schema, definition)

Add new rule with schema prefix. For definition details see constructor description. To disable existing rule use .add(name, null)

.set(options)

Override default options. Missed properties will not be changed.

License

MIT

Keywords

FAQs

Last updated on 02 Jun 2016

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc